<!--
  Copyright JS Foundation and other contributors, http://js.foundation

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<!-- 
  MIT License Copyright 2021, 2022 - Bitpool Pty Ltd
-->


<script type="text/html" data-template-name="Bitpool-Inject">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    </div>

    <div class="form-row node-input-property-container-row bitpoolInjectList">
        <div id="node-input-property-container-list" class="optionsSelector">
            <div class="injectHeading">
                <a>Inject Type </a>
            </div>

            <div class="optionParent">
                <div class="msgOptions discoverOption">
                    <input class="checkbox-round" type="checkbox" id="node-input-doDiscover" class="" style="margin: 0 50px 0 10px;"/>
                    <label style="font-size: 16px; height: min-content; margin-bottom: 0px;" for="node-input-doDiscover">Discover</label> 
                </div>
                <div class="msgOptions pollOption">
                    <input class="checkbox-round" type="checkbox" id="node-input-doPoll" class="" style="margin: 0 50px 0 10px;"/>
                    <label style="font-size: 16px; height: min-content; margin-bottom: 0px;" for="node-input-doPoll">Poll</label> 
                </div>
            </div>

            
        </div>

        <div class="injectHeading" style="margin-top: 20px;">
            <a>Msg Properties</a>
        </div>

        <ol id="node-input-property-container" class="nrEditableList" style="height: 400px !important;"></ol>

    </div>

    <div class="form-row" id="node-once">
        <label for="node-input-once">&nbsp;</label>
        <input type="checkbox" id="node-input-once" style="display:inline-block; width:15px; vertical-align:baseline;">
        <span data-i18n="inject.onstart"></span>&nbsp;
        <input type="text" id="node-input-onceDelay" placeholder="0.1" style="width:45px; height:28px;">&nbsp;
        <span data-i18n="inject.onceDelay"></span>
    </div>

    <div class="form-row">
        <label for=""><i class="fa fa-repeat"></i> <span data-i18n="inject.label.repeat"></span></label>
        <select id="inject-time-type-select">
            <option value="none" data-i18n="inject.none"></option>
            <option value="interval" data-i18n="inject.interval"></option>
            <option value="interval-time" data-i18n="inject.interval-time"></option>
            <option value="time" data-i18n="inject.time"></option>
        </select>
        <input type="hidden" id="node-input-repeat">
        <input type="hidden" id="node-input-crontab">
    </div>

    <div class="form-row inject-time-row hidden" id="inject-time-row-interval">
        <span data-i18n="inject.every"></span>
        <input id="inject-time-interval-count" class="inject-time-count" value="1"></input>
        <select style="width:100px" id="inject-time-interval-units">
            <option value="s" data-i18n="inject.seconds"></option>
            <option value="m" data-i18n="inject.minutes"></option>
            <option value="h" data-i18n="inject.hours"></option>
        </select><br/>
    </div>

    <div class="form-row inject-time-row hidden" id="inject-time-row-interval-time">
        <span data-i18n="inject.every"></span> <select style="width:90px; margin-left:20px;" id="inject-time-interval-time-units" class="inject-time-int-count" value="1">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="10">10</option>
            <option value="12">12</option>
            <option value="15">15</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option value="0">60</option>
        </select> <span data-i18n="inject.minutes"></span><br/>
        <span data-i18n="inject.between"></span> <select id="inject-time-interval-time-start" class="inject-time-times"></select>
        <span data-i18n="inject.and"></span> <select id="inject-time-interval-time-end" class="inject-time-times"></select><br/>
        <div id="inject-time-interval-time-days" class="inject-time-days" style="margin-top:5px">
            <div style="display:inline-block; vertical-align:top; margin-right:5px;" data-i18n="inject.on">on</div>
            <div style="display:inline-block;">
                <div>
                    <label><input type='checkbox' checked value='1'/> <span data-i18n="inject.days.0"></span></label>
                    <label><input type='checkbox' checked value='2'/> <span data-i18n="inject.days.1"></span></label>
                    <label><input type='checkbox' checked value='3'/> <span data-i18n="inject.days.2"></span></label>
                </div>
                <div>
                    <label><input type='checkbox' checked value='4'/> <span data-i18n="inject.days.3"></span></label>
                    <label><input type='checkbox' checked value='5'/> <span data-i18n="inject.days.4"></span></label>
                    <label><input type='checkbox' checked value='6'/> <span data-i18n="inject.days.5"></span></label>
                </div>
                <div>
                    <label><input type='checkbox' checked value='0'/> <span data-i18n="inject.days.6"></span></label>
                </div>
            </div>
        </div>
    </div>

    <div class="form-row inject-time-row hidden" id="inject-time-row-time">
        <span data-i18n="inject.at"></span> <input type="text" id="inject-time-time" value="12:00"></input><br/>
        <div id="inject-time-time-days" class="inject-time-days">
            <div style="display:inline-block; vertical-align:top; margin-right:5px;" data-i18n="inject.on"></div>
            <div style="display:inline-block;">
                <div>
                    <label><input type='checkbox' checked value='1'/> <span data-i18n="inject.days.0"></span></label>
                    <label><input type='checkbox' checked value='2'/> <span data-i18n="inject.days.1"></span></label>
                    <label><input type='checkbox' checked value='3'/> <span data-i18n="inject.days.2"></span></label>
                </div>
                <div>
                    <label><input type='checkbox' checked value='4'/> <span data-i18n="inject.days.3"></span></label>
                    <label><input type='checkbox' checked value='5'/> <span data-i18n="inject.days.4"></span></label>
                    <label><input type='checkbox' checked value='6'/> <span data-i18n="inject.days.5"></span></label>
                </div>
                <div>
                    <label><input type='checkbox' checked value='0'/> <span data-i18n="inject.days.6"></span></label>
                </div>
            </div>
        </div>
    </div>

</script>
<style>
    .optionParent {
        display: flex;
    }
    .injectHeading > a {
        margin: 0;
        font-weight: 600;
        font-size: 14px;
    }
    .injectHeading {
        border-bottom: 1px solid #cbcbcb;
        text-align: start;
        height: 30px;
    }
    .checkbox-round {
        width: 13px !important;
        height: 13px !important;
        background-color: white;
        border-radius: 50%;
        vertical-align: middle;
        border: 1px solid #ddd;
        appearance: none;
        -webkit-appearance: none;
        outline: none;
        cursor: pointer;
    }
    .checkbox-round:checked {
        background-color: #00AEEF;
    }
    .checkbox-round:focus {
        outline: none !important;
    }
    .msgOptions {
        border: 1px solid #cbcbcb;
        border-radius: 4px;
        height: 35px;
        transition: 1s;
        display: flex;
        flex-direction: row;
        justify-content: space-evenly;
        align-items: center;
        cursor: pointer;
        width: 50%;
    }
    .msgOptions:hover {
        border: 1px solid #00AEEF;
        transition: 1s;
        background-color: #f5fcff;
    }
    .discoverOption {
        margin-top: 15px;
        width: 180px;
        margin-right: 20px;
        margin-left: auto;
    }
    .pollOption {
        margin-top: 15px;
        width: 180px;
        margin-right: auto;
    }
    .optionsSelector {
        min-height: 90px !important;
        max-height: none !important;
        display: flex;
        flex-direction: column;
        flex-wrap: nowrap;
        justify-content: space-around;
    } 

    .bitpoolInjectList > .red-ui-editableList > .red-ui-editableList-container {
        min-height: 120px !important;
        max-height: none;
        overflow-y: scroll; 
        height: 410px !important;
    }

    /* node-red css */

    .inject-time-row {
        padding-left: 110px;
    }
    .inject-time-row select {
        margin: 3px 0;
    }
    .inject-time-days label {
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        vertical-align: baseline;
        width: 100px;
    }
    .inject-time-days input {
        width: auto !important;
        vertical-align: baseline !important;
    }
    .inject-time-times {
        width: 90px !important;
    }
    #inject-time-time {
        width: 75px;
        margin-left: 8px;
        margin-bottom: 8px;
    }
    .inject-time-count {
        padding-left: 3px !important;
        width: 80px !important;
    }
</style>

<script type="text/javascript">
(function() {

    function resizeDialog(size) {
        size = size || { height: $(".red-ui-tray-content form").height() }
        var rows = $("#dialog-form>div:not(.node-input-property-container-row):visible");
        var height = size.height;
        for (var i=0; i<rows.length; i++) {
            height -= $(rows[i]).outerHeight(true);
        }
        var editorRow = $("#dialog-form>div.node-input-property-container-row");
        height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom")));
        height += 16;
        $("#node-input-property-container").editableList('height',height);
    }
    /** Retrieve editableList items (refactored for re-use in the form inject button)*/
    function getProps(el, legacy) {
        var result = {
            props: []
        }
        el.each(function(i) {
            var prop = $(this);
            var p = {
                p:prop.find(".node-input-prop-property-name").typedInput('value')
            };
            if (p.p) {
                p.v = prop.find(".node-input-prop-property-value").typedInput('value');
                p.vt = prop.find(".node-input-prop-property-value").typedInput('type');
                if(legacy) {
                    if (p.p === "payload") { // save payload to old "legacy" property
                        result.payloadType = p.vt;
                        result.payload = p.v;
                        delete p.v;
                        delete p.vt;
                    } else if (p.p === "topic" && p.vt === "str") {
                        result.topic = p.v;
                        delete p.v;
                    }
                }
                result.props.push(p);
            }
        });
        return result;
    }
    /** Perform inject, optionally sending a custom msg (refactored for re-use in the form inject button)*/
    function doInject(node, customMsg) {
        var label = node._def.label.call(node,customMsg?customMsg.__user_inject_props__:undefined);
        if (label.length > 30) {
            label = label.substring(0, 50) + "...";
        }
        label = label.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        $.ajax({
            url: "inject/" + node.id,
            type: "POST",
            data: JSON.stringify(customMsg||{}),
            contentType: "application/json; charset=utf-8",
            success: function (resp) {
                RED.notify(node._("inject.success", { label: label }), { type: "success", id: "inject", timeout: 2000 });
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 404) {
                    RED.notify(node._("common.notification.error", { message: node._("common.notification.errors.not-deployed") }), "error");
                } else if (jqXHR.status == 500) {
                    RED.notify(node._("common.notification.error", { message: node._("inject.errors.failed") }), "error");
                } else if (jqXHR.status == 0) {
                    RED.notify(node._("common.notification.error", { message: node._("common.notification.errors.no-response") }), "error");
                } else {
                    RED.notify(node._("common.notification.error", { message: node._("common.notification.errors.unexpected", { status: jqXHR.status, message: textStatus }) }), "error");
                }
            }
        });
    }
    RED.nodes.registerType('Bitpool-Inject',{
        category: 'Bitpool BACnet',
        color: '#00aeef',
        defaults: {
            name: {value:""},
            props:{value:[{p:"payload"},{p:"topic",vt:"str"}], validate:function(v) {
                    if (!v || v.length === 0) { return true }
                    for (var i=0;i<v.length;i++) {
                        if (/msg|flow|global/.test(v[i].vt)) {
                            if (!RED.utils.validatePropertyExpression(v[i].v)) {
                                return false;
                            }
                        } else if (v[i].vt === "jsonata") {
                            try{jsonata(v[i].v);}catch(e){return false;}
                        } else if (v[i].vt === "json") {
                            try{JSON.parse(v[i].v);}catch(e){return false;}
                        }
                    }
                    return true;
                }
            },
            repeat: {value:"", validate:function(v) { return ((v === "") || (RED.validators.number(v) && (v >= 0) && (v <= 2147483))) }},
            crontab: {value:""},
            once: {value:false},
            onceDelay: {value:0.1},
            topic: {value:""},
            payload: {value:"", validate: RED.validators.typedInput("payloadType")},
            payloadType: {value:"date"},
            doPoll: {value:true},
            doDiscover: {value: false},
        },
        icon: "bitpool.svg",
        inputs:0,
        outputs:1,
        outputLabels: function(index) {
            var lab = '';

            // if only payload and topic - display payload type
            // if only one property - show it's type
            // if more than one property (other than payload and topic) - show "x properties" where x is the number of properties.
            // this.props will not be an array for legacy inject nodes until they are re-deployed
            //
            var props = this.props;
            if (!Array.isArray(props)) {
                props = [
                    { p:"payload", v: this.payload, vt: this.payloadType },
                    { p:"topic", v: this.topic, vt: "str" }
                ]
            }
            if (props) {
                for (var i=0,l=props.length; i<l; i++) {
                    if (i > 0) lab += "\n";
                    if (i === 5) {
                        lab += "... +"+(props.length-5);
                        break;
                    }
                    lab += props[i].p+": ";

                    var propType = props[i].p === "payload"? this.payloadType : props[i].vt;
                    if (propType === "json") {
                        try {
                            var parsedProp = JSON.parse(props[i].p === "payload"? this.payload : props[i].v);
                            propType = typeof parsedProp;
                            if (propType === "object" && Array.isArray(parsedProp)) {
                                propType = "Array";
                            }
                        } catch(e) {
                            propType = "invalid";
                        }
                    }
                    lab += this._("inject.label."+propType);
                }
            }
            return lab;
        },
        paletteLabel: function () {
            return "inject";
        },
        label: function(customProps) {
            return this.name || "inject";
        },
        labelStyle: function() {
            return this.name?"node_label_italic":"";
        },
        oneditprepare: function() {
            var node = this;
            var payloadType = node.payloadType;

            if (node.payloadType == null) {
                if (node.payload == "") {
                    payloadType = "date";
                } else {
                    payloadType = "str";
                }
            } else if (node.payloadType === 'string' || node.payloadType === 'none') {
                payloadType = "str";
            }

            $("#inject-time-type-select").on("change", function() {
                $("#node-input-crontab").val('');
                var id = $("#inject-time-type-select").val();
                $(".inject-time-row").hide();
                $("#inject-time-row-"+id).show();
                if ((id == "none") || (id == "interval") || (id == "interval-time")) {
                    $("#node-once").show();
                }
                else {
                    $("#node-once").hide();
                    $("#node-input-once").prop('checked', false);
                }

                // Scroll down
                var scrollDiv = $("#dialog-form").parent();
                scrollDiv.scrollTop(scrollDiv.prop('scrollHeight'));
                resizeDialog();
            });

            $("#node-input-once").on("change", function() {
                $("#node-input-onceDelay").attr('disabled', !$("#node-input-once").prop('checked'));
            })

            $(".inject-time-times").each(function() {
                for (var i=0; i<24; i++) {
                    var l = (i<10?"0":"")+i+":00";
                    $(this).append($("<option></option>").val(i).text(l));
                }
            });
            $("<option></option>").val(24).text("00:00").appendTo("#inject-time-interval-time-end");
            $("#inject-time-interval-time-start").on("change", function() {
                var start = Number($("#inject-time-interval-time-start").val());
                var end = Number($("#inject-time-interval-time-end").val());
                $("#inject-time-interval-time-end option").remove();
                for (var i=start+1; i<25; i++) {
                    var l = (i<10?"0":"")+i+":00";
                    if (i==24) {
                        l = "00:00";
                    }
                    var opt = $("<option></option>").val(i).text(l).appendTo("#inject-time-interval-time-end");
                    if (i === end) {
                        opt.attr("selected","selected");
                    }
                }
            });

            $(".inject-time-count").spinner({
                //max:60,
                min:1
            });

            var repeattype = "none";
            if (node.repeat != "" && node.repeat != 0) {
                repeattype = "interval";
                var r = "s";
                var c = node.repeat;
                if (node.repeat % 60 === 0) { r = "m"; c = c/60; }
                if (node.repeat % 1440 === 0) { r = "h"; c = c/60; }
                $("#inject-time-interval-count").val(c);
                $("#inject-time-interval-units").val(r);
                $("#inject-time-interval-days").prop("disabled","disabled");
            } else if (node.crontab) {
                var cronparts = node.crontab.split(" ");
                var days = cronparts[4];
                if (!isNaN(cronparts[0]) && !isNaN(cronparts[1])) {
                    repeattype = "time";
                    // Fixed time
                    var time = cronparts[1]+":"+cronparts[0];
                    $("#inject-time-time").val(time);
                    $("#inject-time-type-select").val("s");
                    if (days == "*") {
                        $("#inject-time-time-days input[type=checkbox]").prop("checked",true);
                    } else {
                        $("#inject-time-time-days input[type=checkbox]").removeAttr("checked");
                        days.split(",").forEach(function(v) {
                            $("#inject-time-time-days [value=" + v + "]").prop("checked", true);
                        });
                    }
                } else {
                    repeattype = "interval-time";
                    // interval - time period
                    var minutes = cronparts[0].slice(2);
                    if (minutes === "") { minutes = "0"; }
                    $("#inject-time-interval-time-units").val(minutes);
                    if (days == "*") {
                        $("#inject-time-interval-time-days input[type=checkbox]").prop("checked",true);
                    } else {
                        $("#inject-time-interval-time-days input[type=checkbox]").removeAttr("checked");
                        days.split(",").forEach(function(v) {
                            $("#inject-time-interval-time-days [value=" + v + "]").prop("checked", true);
                        });
                    }
                    var time = cronparts[1];
                    var timeparts = time.split(",");
                    var start;
                    var end;
                    if (timeparts.length == 1) {
                        // 0 or 0-10
                        var hours = timeparts[0].split("-");
                        if (hours.length == 1) {
                            if (hours[0] === "") {
                                start = "0";
                                end = "0";
                            }
                            else {
                                start = hours[0];
                                end = Number(hours[0])+1;
                            }
                        } else {
                            start = hours[0];
                            end = Number(hours[1])+1;
                        }
                    } else {
                        // 23,0 or 17-23,0-10 or 23,0-2 or 17-23,0
                        var startparts = timeparts[0].split("-");
                        start = startparts[0];

                        var endparts = timeparts[1].split("-");
                        if (endparts.length == 1) {
                            end = Number(endparts[0])+1;
                        } else {
                            end = Number(endparts[1])+1;
                        }
                    }
                    $("#inject-time-interval-time-end").val(end);
                    $("#inject-time-interval-time-start").val(start);

                }
            } else {
                $("#inject-time-type-select").val("none");
            }

            $(".inject-time-row").hide();
            $("#inject-time-type-select").val(repeattype);
            $("#inject-time-row-"+repeattype).show();

            /* */

            var eList = $('#node-input-property-container-list').css('min-height','120px').css('min-width','450px');
            var eList2 = $('#node-input-property-container').css('min-height','120px').css('min-width','450px');

            eList2.editableList({
                buttons: [
                    {
                        id: "node-inject-test-inject-button",
                        label: node._("inject.injectNow"),
                        click: function(e) {
                            var items = eList2.editableList('items');
                            var props = getProps(items);
                            var m = {__user_inject_props__: props.props};
                            doInject(node, m);
                        }
                    }
                ],
                addItem: function(container,i,opt) {
                    var prop = opt;
                    if (!prop.hasOwnProperty('p')) {
                        prop = {p:"",v:"",vt:"str"};
                    }
                    container.css({
                        overflow: 'hidden',
                        whiteSpace: 'nowrap'
                    });
                    var row = $('<div/>').appendTo(container);

                    var propertyName = $('<input/>',{class:"node-input-prop-property-name",type:"text"})
                        .css("width","30%")
                        .appendTo(row)
                        .typedInput({types:['msg']});

                    $('<div/>',{style: 'display:inline-block; padding:0px 6px;'})
                        .text('=')
                        .appendTo(row);

                    var propertyValue = $('<input/>',{class:"node-input-prop-property-value",type:"text"})
                        .css("width","calc(70% - 30px)")
                        .appendTo(row)
                        .typedInput({default:prop.vt || 'str',types:['flow','global','str','num','bool','json','bin','date','jsonata','env','msg']});

                    propertyName.typedInput('value',prop.p);
                    propertyValue.typedInput('value',prop.v);
                },
                removable: true,
                sortable: true
            });

            $('#node-inject-test-inject-button').css("float", "right").css("margin-right", "unset");

            if (RED.nodes.subflow(node.z)) {
                $('#node-inject-test-inject-button').attr("disabled",true);
            }

            if (!node.props) {
                var payload = {
                    p:'payload',
                    v: node.payload ? node.payload : '',
                    vt:payloadType ? payloadType : 'date'
                };
                var topic = {
                    p:'topic',
                    v: node.topic ? node.topic : '',
                    vt:'str'
                }
                node.props = [payload,topic];
            }

            for (var i=0; i<node.props.length; i++) {
                var prop = node.props[i];
                var newProp = { p: prop.p, v: prop.v, vt: prop.vt };
                if (newProp.v === undefined) {
                    if (prop.p === 'payload') {
                        newProp.v = node.payload ? node.payload : '';
                        newProp.vt = payloadType ? payloadType : 'date';
                    } else if (prop.p === 'topic' && prop.vt === "str") {
                        newProp.v =  node.topic ? node.topic : '';
                    }
                }
                if (newProp.vt === "string") {
                    // Fix bug in pre 2.1 where an old Inject node might have
                    // a migrated rule with type 'string' not 'str'
                    newProp.vt = "str";
                }
                eList2.editableList('addItem',newProp);
            }

            $("#inject-time-type-select").trigger("change");
            $("#inject-time-interval-time-start").trigger("change");

        },
        oneditsave: function() {
            var repeat = "";
            var crontab = "";
            var type = $("#inject-time-type-select").val();
            if (type == "none") {
                // nothing
            } else if (type == "interval") {
                var count = $("#inject-time-interval-count").val();
                var units = $("#inject-time-interval-units").val();
                if (units == "s") {
                    repeat = count;
                } else {
                    if (units == "m") {
                        //crontab = "*/"+count+" * * * "+days;
                        repeat = count * 60;
                    } else if (units == "h") {
                        //crontab = "0 */"+count+" * * "+days;
                        repeat = count * 60 * 60;
                    }
                }
            } else if (type == "interval-time") {
                repeat = "";
                var count = $("#inject-time-interval-time-units").val();
                var startTime = Number($("#inject-time-interval-time-start").val());
                var endTime = Number($("#inject-time-interval-time-end").val());
                var days = $('#inject-time-interval-time-days input[type=checkbox]:checked').map(function(_, el) {
                    return $(el).val()
                }).get();
                if (days.length == 0) {
                    crontab = "";
                } else {
                    if (days.length == 7) {
                        days="*";
                    } else {
                        days = days.join(",");
                    }
                    var timerange = "";
                    if (endTime == 0) {
                        timerange = startTime+"-23";
                    } else if (startTime+1 < endTime) {
                        timerange = startTime+"-"+(endTime-1);
                    } else if (startTime+1 == endTime) {
                        timerange = startTime;
                    } else {
                        var startpart = "";
                        var endpart = "";
                        if (startTime == 23) {
                            startpart = "23";
                        } else {
                            startpart = startTime+"-23";
                        }
                        if (endTime == 1) {
                            endpart = "0";
                        } else {
                            endpart = "0-"+(endTime-1);
                        }
                        timerange = startpart+","+endpart;
                    }
                    if (count === "0") {
                        crontab = count+" "+timerange+" * * "+days;
                    } else {
                        crontab = "*/"+count+" "+timerange+" * * "+days;
                    }
                }
            } else if (type == "time") {
                var time = $("#inject-time-time").val();
                var days = $('#inject-time-time-days  input[type=checkbox]:checked').map(function(_, el) {
                    return $(el).val()
                }).get();
                if (days.length == 0) {
                    crontab = "";
                } else {
                    if (days.length == 7) {
                        days="*";
                    } else {
                        days = days.join(",");
                    }
                    var parts = time.split(":");
                    if (parts.length === 2) {
                        repeat = "";
                        parts[1] = ("00" + (parseInt(parts[1]) % 60)).substr(-2);
                        parts[0] = ("00" + (parseInt(parts[0]) % 24)).substr(-2);
                        crontab = parts[1]+" "+parts[0]+" * * "+days;
                    }
                    else { crontab = ""; }
                }
            }

            $("#node-input-repeat").val(repeat);
            $("#node-input-crontab").val(crontab);

            /* Gather the properties */
            var items = $("#node-input-property-container").editableList('items');
            delete this.payloadType;
            delete this.payload;
            this.topic = "";
            var result = getProps(items, true);
            this.props = result.props;
            if(result.hasOwnProperty('payloadType')) { this.payloadType = result.payloadType; };
            if(result.hasOwnProperty('payload')) { this.payload = result.payload; };
            if(result.hasOwnProperty('topic')) { this.topic = result.topic; };
        },
        button: {
            enabled: function() {
                return !this.changed
            },
            onclick: function () {
                if (this.changed) {
                    return RED.notify(RED._("notification.warning", { message: RED._("notification.warnings.undeployedChanges") }), "warning");
                }
                doInject(this);
            }
        },
        oneditresize: resizeDialog
    });
})();
</script>

<script type="text/html" data-help-name="Bitpool-Inject">
    <p> An extention of the node-red inject node, including the simple button options tailored for the bitpool-BACnet node  </p>

    <h3><strong>Discover</strong></h3>
    <ol class="node-ports">
        <p>
            Used to send the BACnet WhoIs command. This will broadcast on the broadcast address specified in the gateway node.
            This option must link to the gateway node directly
        </p>
    
    </ol>

    <h3><strong>Poll</strong></h3>
    <ol class="node-ports">
        <p>
            Used as basic trigger to start read or write functions.
            This option must link to a Read or Write node directly.
        </p>
     
    </ol>

    <h3><strong>Examples</strong></h3>
            <p>For example flows, please use the examples section for this node. These examples can be found at: Node-red hamburger menu on top right -> Import -> Examples -> @bitpoolos/edge-bacnet</p>
            <p>To find captured examples of settings and flows, please go to our wiki <a href="https://wiki.bitpool.com/en/edge/apps/bitpool-edge/nr-bacnet">here</a></p>


    <h3>Resources:</h3>
    <p><a href="https://youtu.be/4K7mVxfvfbc">Video Walk-through </a></p>
    <h4><strong>Online Docs:</strong></h4>
    <ul type="1">
        <li><a href="https://www.bitpool.com/">bitpool.com</a> - check us out here.</li>
        <li><a href="https://app.bitpool.com/">app.bitpool.com</a> - set up your account.</li>
        <li><a href="https://wiki.bitpool.com/">wiki.bitpool.com</a> - find more documentation.</li>
        <li><a href="https://bacnet.org/">BACnet</a> - find more about the protocol.</li>
    </ul>
</script>